#!/usr/bin/env python
import json
import time

import pika
import sys

credentials = pika.PlainCredentials(username="test", password="test")
connection = pika.BlockingConnection(
    # pika.ConnectionParameters(host='192.168.159.135', credentials=credentials)
    pika.ConnectionParameters(host='192.168.198.132', credentials=credentials)
)


def send():
    send_channel = connection.channel()
    send_channel.queue_declare(queue='send', durable=True)
    # 发送任务
    ip = "192.168.1.1"
    for port in range(1, 1000):
        message = json.dumps({"IP": ip, "PORT": port}).encode("utf8")
        # time.sleep(0.5)
        send_channel.basic_publish(
            exchange='',
            routing_key='send',
            body=message,
            properties=pika.BasicProperties(
                delivery_mode=2,  # make message persistent
            ))
        print(f"-----> {ip}:{port}")


def recv():
    def on_recv(ch, method, properties, body):
        print("<----- %r" % body.decode("utf8"))
    print("[+] Start recv")
    # 接受请求
    recv_channel = connection.channel()
    recv_channel.queue_declare(queue='recv', durable=True)
    # 一次处理30条数据
    recv_channel.basic_qos(prefetch_count=30)
    recv_channel.basic_consume(queue='recv', on_message_callback=on_recv, auto_ack=True)
    recv_channel.start_consuming()
    # while True:



if __name__ == '__main__':
    send()
    recv()

